package com.pillpoppers.pillbox;

import android.app.ListFragment;
import android.app.LoaderManager;
import android.content.Context;
import android.content.CursorLoader;
import android.content.Intent;
import android.content.Loader;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;

import com.pillpoppers.pillbox.contentprovider.PillContentProvider;
import com.pillpoppers.pillbox.database.PillTable;

public class PillListFragment extends ListFragment implements LoaderManager.LoaderCallbacks<Cursor>{
	  // Attributes
    private Context context;

    // Elements
    private SimpleCursorAdapter adapter;

	// private static final int DELETE_ID = Menu.FIRST + 1;
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
	{
		// Set attributes
	    context = getActivity();
	    
		View view = inflater.inflate(R.layout.fragment_pills,container, false);
		  fillData();

	    // Return
	    return view;
	}

    private void fillData() 
    {
      // Fields from the database (projection), needs _id column for the adapter to work.
      String[] from = new String[] { PillTable.COLUMN_NAME,
    		  PillTable.COLUMN_CURRENT_COUNT, PillTable.COLUMN_MAX_COUNT };
      
      // Fields on the UI to which we map
      int[] to = new int[] { R.id.label, R.id.currentCountTextView, R.id.maxCountTextView };

      getLoaderManager().initLoader(0, null, this);
      adapter = new SimpleCursorAdapter(context, R.layout.pill_row, null, from, to, 0);

      setListAdapter(adapter);
    }

    @Override
    public void onListItemClick(ListView l, View v, int pos, long id) {
    
    		  super.onListItemClick(l, v, pos, id);
    		  Intent i = new Intent(context, AddPillActivity.class);
    		  Uri pillUri = Uri.parse(PillContentProvider.CONTENT_URI + "/" + id);
    		  i.putExtra(PillContentProvider.CONTENT_ITEM_TYPE, pillUri);
    		  startActivity(i);
    	  }
// Dialog above
  
	@Override
	public Loader<Cursor> onCreateLoader(int id, Bundle args) {
		  String[] projection = { PillTable.COLUMN_ID, PillTable.COLUMN_NAME,
				  PillTable.COLUMN_CURRENT_COUNT, PillTable.COLUMN_MAX_COUNT };
		  CursorLoader cursorLoader = new CursorLoader(context,PillContentProvider.CONTENT_URI, projection, null, null, null);
		  return cursorLoader;
	}
	@Override
	public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
	    adapter.swapCursor(data);
		
	}
	@Override
	public void onLoaderReset(Loader<Cursor> loader) {
		  adapter.swapCursor(null);
		
	}
}